<?php if( ! defined('BASEPATH')) exit('No direct script access allowed');
/********************
 *@param function:dswp 信息發送記錄管理
 *@param datetime 2014-01-12
 *@param author abin
 ********************/
class Specs extends Admins_Controller {
	public function __construct(){
	    parent::__construct();
	    $this->data['currentPage']='manages';
	    $this->load->model('categorys_mdl');
	    $this->load->model('specs_mdl');
	    $this->load->model('products_mdl');
        $this->load->model('posprint_mdl');
        $this->load->model('languages_mdl');
        $this->data['type']=$this->settings['default_language'];
        $lan_get = 	$this->input->get('lan','');
        $lan_get = empty($lan_get) ? get_cookie('language') : $lan_get;
        if(empty($lan_get) || !in_array($lan_get,array('zh-tw','english'))){
            $lan_get = 'english';
        }
        $this->lang->load('page', $lan_get);
        set_cookie('language',$lan_get,time()+24*3600*30);
        $this->data['getlang'] = $lan_get;
        $this->data['lang'] =$this->lang->language;
	} 
	public function index(){
        $page = $this->input->get('p',TRUE);
        $page = (!empty($page) && is_numeric($page)) ? intval($page) : 1;
        $limit = $this->settings['default_admin_limit'];
        //$limit =1;
        $offset = ($page - 1) * $limit;
        if($offset < 0){
            redirect('admins/categorys');
        }
        $url_query=$_SERVER['QUERY_STRING'];
        // 保留查詢參數;
        $cookie = array(
            'name'   => 'url_query',
            'value'  => base64_encode($url_query),
            'expire' => '0',
            'path'   => '/',
        );
        $this->input->set_cookie($cookie);
        if(!empty($url_query)){
            $url_query=preg_replace('/&p=(\d+)/','',$url_query);
        }
		$data = array();
        $data['limits'] = $limit;
        $data['offset'] = $offset;
		$data['field'] = 'add_time';
		$data['language_id']=$this->settings['default_language'];
		$query=$this->specs_mdl->get_specs_all($data);

        $this->data['lists'] = $query->result_array();
        $this->data['cats'] = $this->categorys_mdl->get_category_field();
        $this->data['posarea'] = $this->posprint_mdl->get_posprint_field();

        $this->data['lists_count']=$total = $this->db->get('clickrcms_specs')->num_rows();;
        $pagination = '';
        if($this->data['lists_count'] > $limit)
        {
            $this->dpagination->currentPage($page);
            $this->dpagination->items($this->data['lists_count']);
            $this->dpagination->limit($limit);
            $this->dpagination->adjacents(5);
            $this->dpagination->target(site_url('admins/specs').'?'.$url_query);
            $this->dpagination->parameterName('p');
            $this->dpagination->nextLabel($this->data['lang']['orders_lable_19']);
            $this->dpagination->PrevLabel($this->data['lang']['orders_lable_18']);
            $pagination = $this->dpagination->getOutput();
        }
        $this->data['pagination'] = $pagination;

        $this->load->view('admins/specs_list_view',$this->data);
	}
	public function edit(){
		$error = null;	
		$id = (int)$this->input->get_post('id',true);
		$row = array();
		

		if($_SERVER['REQUEST_METHOD']=="POST"){
			$items = $this->input->get_post('items');
			$items_en = $this->input->get_post('items_en');
			$prices = $this->input->post('price');
			$row = $this->input->post();
			$base['name'] = $this->input->post('name');
            $base['is_trans'] = (int)$this->input->post('is_trans');
			if(empty($base['name'])){
				$error = "請輸入規格名稱";
				goto a;
			}
			$base['name_en'] = $this->input->post('name_en');
			$base['name_en'] = empty($base['name_en']) ? $base['name'] : $base['name_en'];
			$base['cat_id'] = (int)$this->input->post('cat_id');
			if(empty($base['cat_id'])){
				$error = "請選擇所屬分類";
				goto a;
			}
			$items = $this->input->post('items');
			if(empty($items)){
				$error = "請輸入規格項";
				goto a;
			}
			$itemss = array();
            $base['pos_id'] = (int)$this->input->post('pos_id');
            if(empty($base['pos_id'])){
                $error = "請選擇打印地點";
                goto a;
            }
            $base['is_pos'] = (int)$this->input->post('is_pos');
			$base['add_time']  =time();
			$base['sort'] = (int)$this->input->post('sort');
			$base['status'] = (int)$this->input->post('status');

			if($id > 0){
				if(!$this->specs_mdl->_edit($base,$id)){
					$error = $this->data['lang']['global_lable_49'];
					goto a;
				}
				//$this->specs_mdl->deleteItem(array('spec_id'=>$id)); 
			}else{
				if(!$id=$this->specs_mdl->add($base)){
					$error = $this->data['lang']['global_lable_49'];
					goto a;
				}	
			}
			$i=0;
			$item_cn = array();
			foreach ($items as $key => $item) {
				if(empty($item)) continue;
				$name = $item;
				//$name_en = empty($items_en[$key]) ? $item : $items_en[$key];
				$name_en = empty($items_en[$key]) ? $item : $items_en[$key];
				$price = (float)$prices[$key];
				if($this->specs_mdl->check_spec_item($key)){
					$this->specs_mdl->_editItem(array('name_en'=>$name_en,'name'=>$name,'price'=>$price),$key);
					continue;
				}
				$item_cn[$i]['name'] = $name;
				$item_cn[$i]['price'] = $price;
				$item_cn[$i]['name_en'] = $name_en;
				$item_cn[$i]['spec_id'] = $id;
				$item_cn[$i]['cat_id'] = $base['cat_id'];
				
				$i++;
			}
			if(is_array($item_cn) && count($item_cn) > 0){
				$this->specs_mdl->addItem($item_cn);
			}
        	$this->nsession->set_flashdata('success', $this->data['lang']['global_lable_48']);
        	$redirect=site_url('admins/specs/index');//獲取列表篩選參數
      		redirect($redirect);
      		exit;
			a:

		}
		if($id>0){
			$row = $this->specs_mdl->get_spec_byid($id);
			if($row){
				$itms = $this->specs_mdl->getItemsBYSpecId($row['id']);
				
				$row['items'] = $itms;
			}
		}
		$this->data['row'] = $row;
		$this->data['form_error'] = $error;

		$this->data['cates'] = $this->categorys_mdl->get_descriptions()->result();

		$this->data['posname'] = $this->db->get('clickrcms_posprint')->result();
		$this->load->view('admins/specs_form_view',$this->data);
	}
	public function delete(){
		$id = (int)$this->input->get_post('id',true);
		if($id>0 && $this->specs_mdl->delete(array('id'=>$id))){
			$code = 'success';
			$msg = $this->data['lang']['global_lable_48'];
		}else{
			$code = 'error';
			$msg = $this->data['lang']['global_lable_49'];
		}
		$this->nsession->set_flashdata($code, $msg);
		$redirect=site_url('admins/specs/index');//獲取列表篩選參數
      	redirect($redirect);
      	exit;
	}
	 
     public function getSpecIems(){
     	$cat_id = (int)$this->input->get_post('cat_id');
     	$product_id = (int)$this->input->get_post('product_id');
     	$htmls = null;
     	header("Content-type:text/html;charset=utf-8");
        $AttrItemSpec= $this->products_mdl->getAttrItemSelect($product_id);
     	if($cat_id){
     		if($product_id > 0){
     			$itemPrice = $this->products_mdl->getItemPriceSelectd($product_id);
     		}
     		$specs = $this->specs_mdl->get_spec_items(array('status'=>1,'cat_id'=>$cat_id))->result_array();
     		if($specs){
                $htmls .= "<table><tr><th colspan='2'><span>规格选择</span></th></tr>";
                $trans = "<tr><th colspan='2'><span>配料选择</span></th></tr>";
                $isTrans = false;
     			foreach($specs as $spec){
                    $html = "<tr>";
                    if($this->data['getlang']=='zh-tw') {
                        $html .= "<th class='spec-name'>" . $spec['name'] . "：</th>";
                    }else{
                        $html .= "<th class='spec-name'>" . $spec['name_en'] . "：</th>";
                    }
		     		$html .= "<th class='spec-items'>";
		     		$items = $this->specs_mdl->getItemsBYSpecId($spec['id']);
                    $class = $spec['is_trans'] == 1 ? 'attr_item' : 'spec_item';
                    if($spec['is_trans'] == 1){
                        $selectItems = array_values($AttrItemSpec);
                    }else{
                        $selectItems = $itemPrice;
                    }
		     		if($items){
		     			foreach ($items as $item) {
		     				$on = '';
		     				if(isset($selectItems) && in_array($item['id'], $selectItems)){
		     					$on = 'on';
		     				}
                            if($this->data['getlang']=='zh-tw') {
                                $html .= "<span class='$class $on' data-price='".$item['price']."' data-item='" . $item['id'] . "' data-spec='" . $item['spec_id'] . "' data-key='" . $item['spec_id'] . "_" . $item['id'] . "'>" . $item['name'] . "</span>";
                            }else{
                                $html .= "<span class='$class $on' data-item='".$item['id']."' data-spec='".$item['spec_id']."' data-key='".$item['spec_id']."_".$item['id']."'>".$item['name_en']."</span>";
                            }
			     		}
		     		}
                    $html .= "</td>";
                    $html .= "</tr>";
                    if($spec['is_trans'] == 1){
                        $trans .= $html;
                        $isTrans = true;
                    }else{
                        $htmls .= $html;
                    }
	     		}
                if($isTrans){
                    $htmls .= $trans;
                }
                $htmls .= "</table>";

                $htmls .= "<div id='spec_item_input'></div>";
                if($isTrans){
                    $Attrinput = '';
                    if($AttrItemSpec){
                        foreach ($AttrItemSpec as $sp => $value) {
                            $Attrinput .= "<input type='hidden' name='attrItems[{$sp}]' value='1' />";
                        }
                    }
                    $htmls .= "<div id='attr_item_input'>{$Attrinput}</div>";
                }
            }
            echo $htmls;
     	}
     }
     public function getSpecItemInput(){
     	$product_id = (int)$this->input->get_post('product_id');
     	$spec_arr = $this->input->get_post('spec_arr');
        $_price = (float)$this->input->get_post('price');
     	if(empty($spec_arr)){
     		exit();
     	}
     	$itemPrice = array();
     	if($product_id > 0){
			$itemPrice = $this->products_mdl->getItemPrice($product_id);
     	}
     	
     	$cat_id = (int)$this->input->post('cat_id');
         $clo_name = array_keys($spec_arr);
         $spec_arr2 = self::combineDika($spec_arr);
         $spec = $this->specs_mdl->getSpecField(array('cat_id'=>$cat_id));
         $specItem = $this->specs_mdl->getSpecItemField(array('cat_id'=>$cat_id));         
         $str = "<table class='table sortable' id='spec_input_tab'>";
         $str .="<thead><tr>";
         // 显示第一行的数据
         //var_dump($clo_name);exit;
         if($clo_name){
             foreach ($clo_name as $k => $v)
             {
                 if(!isset($spec[$v])) continue;
                 if($this->data['getlang']=='zh-tw') {
                     $str .= " <th width='100'><b>{$spec[$v]['name']}</b></th>";
                 }else{
                     $str .= " <th width='100'><b>{$spec[$v]['name_en']}</b></th>";
                 }
             }
         }
         $str .="<th><b>".$this->data['lang']['content_lable_49']."</b></th></tr></thead><tbody class='table'>";
         foreach($spec_arr2 as $k => $v){
         	$str .="<tr>";
         	$item_key_name = array();
            $item_price = $_price;
         	foreach($v as $k2 => $v2)
            {
                 if(!isset($specItem[$v2]['name'])) continue;
                if($this->data['getlang']=='zh-tw') {
                    $str .= "<td>{$specItem[$v2]['name']}</td>";
                }else{
                    $str .= "<td>{$specItem[$v2]['name_en']}</td>";
                }
                 $item_key_name[$v2] = $specItem[$v2]['name'];
                $item_price += (float)$specItem[$v2]['price'];
            }  
            ksort($item_key_name);
            $item_key = implode('_', array_keys($item_key_name));
            $item_name = implode(' ', $item_key_name);
            $price = isset($itemPrice[$item_key]) ? $itemPrice[$item_key]['price'] : 0;
             if($price <= 0){
                 $price = $item_price;
             }
            $str .="<td><input type='hidden' name='item[$item_key][spec_name]' value='".$item_name."'/><input class='price-text' name='item[$item_key][price]' value='".$price."' onkeyup='this.value=this.value.replace(/[^\d.]/g,\"\")' onpaste='this.value=this.value.replace(/[^\d.]/g,\"\")' /></td>";
            $str .="</tr>";           

         }
         $str .= "</tbody></table>";
         echo $str;

     }
    public function getAttrItemInput(){
        $product_id = (int)$this->input->get_post('product_id');
        $attr_arr = $this->input->get_post('attr_arr');
        if(is_array($attr_arr) && count($attr_arr) > 0){
            $attr_arrs = array_keys($attr_arr);
            $specs = $this->specs_mdl->getSpecByIds($attr_arrs);
            if(is_array($specs) && count($specs) > 0){
                $html = "";
                foreach ($specs as $key => $val) {
                    $itemIDs = $this->specs_mdl->_get_itemsBYIds($attr_arr[$val['id']]);
                    if(empty($itemIDs)){
                        continue;
                    }
                    foreach ($itemIDs as $k => $item) {
                        $key = $val['id']."_".$item['id'];
                        $num = 1;
                        $html .= "<input type='hidden' name='attrItems[{$key}]' value='".$num."' />";
                    }
                }
                echo $html;
            }
        }
    }
     /**
      * 多个数组的笛卡尔积
      * @param unknown_type $data
      */
     static public function combineDika() {
         $data = func_get_args();
         $data = current($data);
         $cnt = count($data);
         $result = array();

         $arr1 = array_shift($data);

         foreach($arr1 as $key=>$item)
         {
             $result[] = array($item);
         }
         foreach($data as $key=>$item)
         {
             $result = self::combineArray($result,$item);
         }
         return $result;

     }
     /**
      * 两个数组的笛卡尔积
      * @param unknown_type $arr1
      * @param unknown_type $arr2
      */
     static public function combineArray($arr1,$arr2) {
         $result = array();
         foreach ($arr1 as $item1)
         {
             foreach ($arr2 as $item2)
             {
                 $temp = $item1;
                 $temp[] = $item2;
                 $result[] = $temp;
             }
         }
         return $result;
     }
     public function delSpecItem(){
     	$item_id = (int)$this->input->get_post('item_id');
     	if($item_id > 0 && $result = $this->specs_mdl->deleteItem(array('id'=>$item_id))){
     		exit(json_encode(array('status'=>1,'info'=>'删除成功.')));
     	}
     	exit(json_encode(array('status'=>0,'info'=>'删除失败.')));
     }
}